#include <gdt.h>

gdt_entry gdt[6];
gdt_descriptor gdt_ptr;

void gdt_set_gate(int num, unsigned int base, unsigned int limit, unsigned char access, unsigned char gran)
{
	gdt[num].base_lower = (base & 0xFFFF);
	gdt[num].base_middle = (base >> 16) & 0xFF;
	gdt[num].base_upper = (base >> 24) & 0xFF;
	
	gdt[num].limit_lower = (limit & 0xFFFF);
	
	gdt[num].fl_limit_upper = ((limit >> 16) & 0x0F) | (gran & 0xF0);
	
	gdt[num].access = access;
}

void init_gdt()
{
	gdt_ptr.size = sizeof(gdt_entry)*6-1;
	gdt_ptr.offset = (unsigned int) &gdt;
	
	gdt_set_gate(0, 0, 0, 0, 0);
	gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF);
	gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF);
	gdt_set_gate(3, 0, 0xFFFFFFFF, 0xFA, 0xCF);
	gdt_set_gate(4, 0, 0xFFFFFFFF, 0xF2, 0xCF);
	gdt_set_gate(5, (unsigned int)&global_tss, (unsigned int)&global_tss+sizeof(TSS), 0x89, 0x0F);

	memset(&global_tss, 0, sizeof(TSS));
	global_tss.ss0 = 0x10;
	global_tss.ldt = 0;
	global_tss.ss = 0x00;
	global_tss.ds = global_tss.es = global_tss.fs = global_tss.gs = 0x10;
	global_tss.cs = 0x0B;
	gdt_flush((unsigned int)&gdt_ptr);
	tss_flush(5*sizeof(gdt_entry));
}
